package com.jy.service.filemanager.taskmain;

import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jy.entity.filemanager.TSTaske;
import com.jy.repository.filemanager.TaskMainDao;
import com.jy.service.base.BaseServiceImp;
import com.jy.task.utils.ScheduleTaskUtils;
import com.jy.task.utils.ScheduleUtils;
import com.jy.task.utils.TaskOperLogUtil;

@Service("mainTaskService")
public class TaskMainServiceImp extends BaseServiceImp<TSTaske> implements
		TaskMainService {

	/** 调度工厂Bean */
	@Autowired
	private Scheduler scheduler;

	@Override
	@Transactional
	public int creatTask(TSTaske o) {
		int res = 0;
		try {
			o.setCreateDate(new Date());
			// 当状态为启用时
			if (o.getStatus() != null && o.getStatus() == 1) {
				ScheduleTaskUtils.createScheduleJob(scheduler, o);
			}
			// 更新数据库
			super.insert(o);
			TaskOperLogUtil.saveTaskLog(1, "任务", "新增任务信息");
			res = 1;
		} catch (Exception e) {
			logger.error("创建任务失败", e);
		}
		return res;
	}

	@Override
	@Transactional
	public int updateTask(TSTaske o) {
		int res = 0;
		try {
			TaskMainDao dao = (TaskMainDao) baseDao;
			// if (2 == o.getExecutionMode()) {
			// } else {
			// ScheduleTaskUtils.updateScheduleJob(scheduler, o);
			// }
			ScheduleTaskUtils.deleteScheduleJob(scheduler, o.getTaskCode(),
					o.getProjectId());
			ScheduleTaskUtils.createScheduleJob(scheduler, o);
			// 从数据库查找原信息
			dao.update(o);
			TaskOperLogUtil.saveTaskLog(2, "任务", "修改任务信息");
			res = 1;
		} catch (Exception e) {
			logger.error("创建任务失败", e);
		}
		return res;
	}

	@Override
	@Transactional
	public int deleteTask(TSTaske o) {
		int res = 0;
		try {
			TaskMainDao dao = (TaskMainDao) baseDao;
			// 从数据库查找原信息
			dao.deleteTask(o);
			ScheduleTaskUtils.deleteScheduleJob(scheduler, o.getTaskCode(),
					o.getProjectId());
			TaskOperLogUtil.saveTaskLog(3, "任务", "删除任务信息");
			res = 1;
		} catch (Exception e) {
			logger.error("删除任务失败", e);
		}
		return res;
	}

	@Override
	public TSTaske findTaskById(TSTaske o) {
		TaskMainDao dao = (TaskMainDao) baseDao;
		TSTaske obj = new TSTaske();
		obj = dao.findTaskByPId(o.getId());
		return obj;
	}

	@Override
	public List<TSTaske> findTaskRun() {
		TaskMainDao dao = (TaskMainDao) baseDao;
		List<TSTaske> obj = dao.findTaskRun();
		return obj;
	}

	@Override
	@Transactional
	public int updateNewDate(TSTaske o) {
		int res = 0;
		try {
			TaskMainDao dao = (TaskMainDao) baseDao;
			// 从数据库查找原信息
			dao.updateNewDate(o);
			res = 1;
		} catch (Exception e) {
			logger.error("修改任务失败", e);
		}
		return res;
	}

	@Override
	@Transactional
	public int updateNewStatus(TSTaske o) {
		int res = 0;
		try {
			TaskMainDao dao = (TaskMainDao) baseDao;
			// 从数据库查找原信息
			dao.updateNewStatus(o);
			res = 1;
		} catch (Exception e) {
			logger.error("修改任务失败", e);
		}
		return res;
	}

	@Override
	@Transactional
	public int updateOnlyStatus(TSTaske o) {
		int res = 0;
		try {
			TaskMainDao dao = (TaskMainDao) baseDao;
			// 从数据库查找原信息
			dao.updateOnlyStatus(o);
			res = 1;
		} catch (Exception e) {
			logger.error("修改任务失败", e);
		}
		return res;
	}

	@Override
	@Transactional
	public void deleteNoUserTask(TSTaske o) {
		try {
			TaskMainDao dao = (TaskMainDao) baseDao;
			o = dao.findTaskByPId(o.getId());
			ScheduleTaskUtils.deleteScheduleJob(scheduler, o.getTaskCode(),
					o.getProjectId());
			// 修改任务状态
			o.setStatus(4);
			dao.updateNewStatus(o);
		} catch (Exception e) {
			logger.error("修改任务失败", e);
		}
	}

	/**
	 * 暂停定时任务
	 */
	@Override
	public void stopTaskJob(TSTaske o) {
		try {
			ScheduleTaskUtils.pauseJob(scheduler, o.getTaskCode(),
					o.getProjectId());
			TaskMainDao dao = (TaskMainDao) baseDao;
			o.setStatus(2);// 暂停
			dao.updateNewStatus(o);
		} catch (SchedulerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 恢复定时任务
	 */
	@Override
	public void resetTaskJob(TSTaske o) {
		try {
			ScheduleTaskUtils.resumeJob(scheduler, o.getTaskCode(),
					o.getProjectId());
			TaskMainDao dao = (TaskMainDao) baseDao;
			o.setStatus(1);// 恢复
			dao.updateNewStatus(o);
		} catch (SchedulerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void initTaskJob() {
		// 查找启用的任务
		TSTaske aj = new TSTaske();
		TaskMainDao dao = (TaskMainDao) baseDao;
		List<TSTaske> taskList = dao.find(aj);
		if (CollectionUtils.isNotEmpty(taskList)) {
			for (TSTaske obj : taskList) {
				if (obj.getStatus() == 5) {
					obj.setStatus(1);
					dao.updateNewStatus(obj);
				}
				if (obj.getStatus() == 1 || obj.getStatus() == 2) {
					CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(
							scheduler, obj.getTaskCode(), obj.getProjectId());
					try {
						if (cronTrigger == null) {
							// 不存在，创建一个
							ScheduleTaskUtils.createScheduleJob(scheduler, obj);
							if (obj.getStatus() == 2) {
								ScheduleTaskUtils.pauseJob(scheduler,
										obj.getTaskCode(), obj.getProjectId());
							}

						} else {
							// 已存在，那么更新相应的定时设置
							ScheduleTaskUtils.updateScheduleJob(scheduler, obj);
						}
					} catch (Exception e) {
						logger.error("创建定时任务失败", e);
					}
				}
			}
		}
	}

	@Override
	public void initCheckTaskJob() {
		try {
			ScheduleTaskUtils.createCheckIsValid(scheduler);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public int findRealHiTask(String type) {
		TaskMainDao dao = (TaskMainDao) baseDao;
		return dao.findRealHiTask(type);
	}

}
